<template>
	<view class="schedule-container">
		<!-- 状态筛选区域 -->
		<view class="status-filter">
			<uni-segmented-control :current="current" :values="items" :styleType="styleType" :active-color="activeColor"
				@clickItem="onClickItem" />
		</view>

		<!-- 列表区域 -->
		<scroll-view scroll-y="true" class="schedule-list" @refresherrefresh="onRefresh" :refresher-enabled="true">
			<view v-if="data.length === 0" class="empty-state">
				<image src="/static/avatar/empty.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无{{items[current]}}的任务</text>
			</view>

			<view v-for="(item,index) in data" :key="index" class="schedule-card" :class="'status-' + item.status">
				<!-- 卡片头部 -->
				<view class="card-header">
					<view class="user-info">
						<image :src="item.avatar || '/static/avatar/empty.png'" class="user-avatar"></image>
						<view>
							<text class="username">{{ item.username }}</text>
							<text class="mobile">联系电话：{{ item.mobile }}</text>
						</view>
					</view>
					<view class="status-tag" :class="'status-' + item.status">
						{{ statusText[item.status] }}
					</view>
				</view>

				<!-- 行程信息 -->
				<view class="route-info">
					<view class="route-item">
						<uni-icons type="location-filled" size="16" color="#4a90e2"></uni-icons>
						<text class="route-text">{{ item.boarding_location }}</text>
					</view>
					<view class="divider">
						<view class="line"></view>
						<uni-icons type="arrowright" size="16" color="#999"></uni-icons>
					</view>
					<view class="route-item">
						<uni-icons type="map-pin" size="16" color="#e74c3c"></uni-icons>
						<text class="route-text">{{ item.destination }}</text>
					</view>
				</view>

				<!-- 详细信息 -->
				<view class="detail-info">
					<view class="detail-item">
						<uni-icons type="calendar" size="16" color="#666"></uni-icons>
						<text>出发时间: {{ item.start_time }}</text>
					</view>
					<view class="detail-item">
						<uni-icons type="group" size="16" color="#666"></uni-icons>
						<text>乘车人数: {{ item.p_num }}人</text>
					</view>
					<view class="detail-item">
						<uni-icons type="compose" size="16" color="#666"></uni-icons>
						<text>事由: {{ item.reason }}</text>
					</view>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="action-btn view-btn" @click="viewClick(item._id)">
						查看详情
					</button>
					<button v-if="item.status == 1" class="action-btn complete-btn" @click="completeClick(item._id)">
						完成任务
					</button>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				role: -1,
				current: 0,
				activeColor: '#2979ff',
				styleType: 'text',
				items: ['未完成', '已完成'],
				statusText: {
					1: "进行中",
					2: "已完成"
				},
				userinfo: {},
				data: []
			}
		},
		mounted() {
			this.userinfo = uni.getStorageSync('userInfo')
			if (this.userinfo._id) {
				this.role = this.userinfo.role.value
				this.fetchData(Number(this.userinfo.mobile))
			}
		},
		methods: {
			async fetchData(mobile) {
				try {
					const obj = uniCloud.importObject('schedules')
					const res = await obj.getCarSchedulesByDriverMobile({
						driver_mobile: mobile,
						status: this.current + 1
					})

					if (res.code == 0) {
						this.data = res.data.map(item => ({
							...item,
							status: item.status === 1 ? 1 : 2
						}))
					} else {
						this.data = []
					}
				} finally {
					uni.hideLoading()
				}
			},
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
					this.fetchData(Number(this.userinfo.mobile))
				}
			},
			onRefresh() {
				this.fetchData(Number(this.userinfo.mobile)).finally(() => {
					uni.stopPullDownRefresh()
				})
			},
			completeClick(id) {
				// //console.log(id)
				let event = {
					_id: id,
					data: {
						status: 2,
						end_time: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
					}
				}
				this.updateCarSchedules(event).then(() => {
					//更新司机状态
					this.updateDriverStatus()
					// 更新成功后重新获取数据					
					this.fetchData(Number(this.userinfo.mobile)) // 确保使用最新参数
				})
			},
			viewClick(id) {
				// //console.log(id)
				// uni.navigateTo({
				// 	url: `/pagesA/car/info?_id=${id}`
				// })
				uni.$router.to({
					url: '/pagesA/car/info',
					params: {
						_id: id
					}
				})
			},

			async updateDriverStatus() {
				const obj = uniCloud.importObject('driver')
				let event = {
					mobile: Number(this.userinfo.mobile),
					status: 0
				}
				const res = obj.updateDriverStatusByMobile(event).then(r => {
					if (r.code == 0) {
						// //console.log('r', r)
					} else {
						// //console.log(r.message)
					}
				})
			},

			async updateCarSchedules(e) { // 改为async/await方式
				try {
					const obj = uniCloud.importObject('schedules')
					const res = await obj.updateCarSchedules(e)
					if (res.code === 0) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						})
						return true // 返回成功状态
					}
				} catch (e) {
					//console.error(e)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
					return false
				}
			}
		}
	}
</script>

<style lang="scss">
	/* 保持与schedules_list相同的样式 */
	$primary-color: #2979ff;
	$success-color: #18bc37;
	$warning-color: #f3a73f;
	$danger-color: #e54d42;

	.schedule-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
		padding: 20rpx;
	}

	.status-filter {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
	}

	.schedule-list {
		flex: 1;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		.empty-image {
			width: 300rpx;
			height: 300rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 30rpx;
			color: #999;
			margin-top: 30rpx;
		}
	}

	.schedule-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		position: relative;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			left: 0;
			top: 0;
			bottom: 0;
			width: 8rpx;
		}

		&.status-1::before {
			background: #4facfe;
		}

		&.status-2::before {
			background: #43e97b;
		}
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 20rpx;
	}

	.user-info {
		display: flex;
		align-items: center;

		.user-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
			background: #f0f7ff;
		}

		.username {
			font-size: 32rpx;
			font-weight: bold;
			display: block;
		}

		.mobile {
			font-size: 26rpx;
			color: #666;
		}
	}

	.status-tag {
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		font-size: 24rpx;
		font-weight: bold;

		&.status-1 {
			background: rgba(79, 172, 254, 0.2);
			color: #4facfe;
		}

		&.status-2 {
			background: rgba(67, 233, 123, 0.2);
			color: #43e97b;
		}
	}

	.route-info {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;

		.route-item {
			flex: 1;
			display: flex;
			align-items: center;
			padding: 12rpx 0;
		}

		.route-text {
			margin-left: 10rpx;
			font-size: 28rpx;
		}

		.divider {
			width: 80rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.line {
				width: 40rpx;
				height: 2rpx;
				background: #ddd;
				margin: 8rpx 0;
			}
		}
	}

	.detail-info {
		.detail-item {
			display: flex;
			align-items: center;
			padding: 10rpx 0;
			font-size: 28rpx;
			color: #666;

			uni-icons {
				margin-right: 10rpx;
			}
		}
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
		margin-top: 30rpx;
		gap: 20rpx;

		.action-btn {
			padding: 0 30rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			border: none;

			&::after {
				border: none;
			}

			&.view-btn {
				background: #f0f4f8;
				color: $primary-color;
			}

			&.complete-btn {
				background: rgba($success-color, 0.1);
				color: $success-color;
			}
		}
	}
</style>